// pages/hello/chat/chat.js
var app = getApp();
Page({
    data: {
        producerName: '卖家',
        nickname: '小投',
        userInfo: null,
        message:'',
        socketTask:null,
        socketOpen : false,
        socketMsgQueue:[],
        msgList:[],
        list:['1','2']
    },
    sendMessage:function(){
        let that = this;
        that.data.socketMsgQueue.push(that.data.message);
        that.data.msgList.push(that.data.message);
        that.setData({ msgList: that.data.msgList});
        that.setData({ message:''});
        for (let i = 0; i < that.data.socketMsgQueue.length; i++) {
            this.sendSocketMessage(that.data.socketMsgQueue[i])
        };
        that.setData({ socketMsgQueue:[]});
    },
    bindMsg(e){
        this.setData({ message: e.detail.value});
    },
    sendSocketMessage(msg) {
        let that = this;
        if(this.data.socketOpen) {
            this.data.socketTask.send({
                data: msg
            })
        } else {
            that.socketMsgQueue.push(msg)
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        let that = this;
        wx.setNavigationBarTitle({
            title: that.data.producerName,
        })
        let userInfo = wx.getStorageSync('userInfo');
        that.setData({ userInfo: userInfo});
        console.log(this.data.userInfo);
        console.log(this.data.userInfo.avatarUrl);
        let socketTask = wx.connectSocket({
            url: 'ws://192.168.9.69:8910/websocket/wizardc',
            success: function(){
                console.log("成功建立连接");
            },
            method: "GET"
        });
        this.setData({ socketTask: socketTask});
        socketTask.onOpen(function () {
            console.log("onopen！");
            that.data.socketOpen = true;
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    }
})